<template>
  <div>
    <!-- 筛选 -->
    <div class="search-container">
      <el-input
        v-model="filterForm.productName"
        size="medium"
        style="margin-right:20px;width:300px"
        placeholder="请输入名称搜索"
        @keyup.enter.native="searchByKeyword"
      />
      <el-button
        type="primary"
        size="medium"
        round
        icon="el-icon-search"
        :loading="searchLoading"
        @click="searchByKeyword"
      >查 询</el-button>
    </div>

    <el-table
      v-loading="tableLoading"
      :data="list"
      border
      stripe
      style="width: 100%"
      empty-text="暂无数据"
      :row-style="{height:'54px'}"
    >
      <el-table-column prop="name" label="名称" fixed />
      <el-table-column
        v-if="tabName==='1'||tabName==='2'"
        prop="periodDuration"
        width="100px"
        label="时长/小时"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.periodDuration/60 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="basePrice" width="100px" label="基础价格/元">
        <template slot-scope="scope">
          <span>{{ scope.row.basePrice/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="tabName==='1'||tabName==='2'" prop="weekdayLimit" label="可使用时段">
        <template slot-scope="scope">
          <span v-if="scope.row.weekdayLimit">
            <span v-for="(item,index) in weekOptions" :key="index">
              <span v-if="scope.row.weekdayLimit.split(',').includes(item.value)">{{ item.label }}</span>
            </span>
          </span>
          <span v-else>不限</span>
        </template>
      </el-table-column>
      <el-table-column v-if="tabName==='1'||tabName==='2'" prop="periodStartTime" label="可使用时间">
        <template slot-scope="scope">
          <span
            v-if="scope.row.periodStartTime||scope.row.periodEndTime"
          >{{ scope.row.periodStartTime|minsToHourMins }}~{{ scope.row.periodEndTime|minsToHourMins }}</span>
          <span v-else>00:00~24:00</span>
        </template>
      </el-table-column>
      <el-table-column v-if="!isCopy" prop="description" label="资源说明" />
      <el-table-column v-if="!isCopy" prop="attrList" label="资源参数" :formatter="formatAttrList" />
      <el-table-column
        v-if="!isCopy&&(tabName==='0'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_FD_EDIT')||
          tabName==='1'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_HR_EDIT')||
          tabName==='2'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_EDIT'))"
        prop="ranking"
        label="排序"
        width="180"
      >
        <template slot-scope="scope">
          <template v-if="isEditRanking&&scope.row.id==rankingForm.id">
            <el-input
              v-model.number="rankingForm.ranking"
              class="ranking-input"
              maxlength="4"
              size="mini"
              @keyup.enter.native="confirmEditRanking(scope.row)"
            />
          </template>
          <span v-else>{{ scope.row.ranking }}</span>
          <el-button
            v-if="isEditRanking&&scope.row.id==rankingForm.id"
            type="text"
            size="small"
            @click="confirmEditRanking(scope.row)"
          >确定</el-button>
          <el-button
            v-if="isEditRanking&&scope.row.id==rankingForm.id"
            type="text"
            @click="cancelEditRanking(scope.row)"
          >取消</el-button>
          <el-button
            v-else
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="editRanking(scope.row,scope.$index)"
          >排序</el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="!isCopy" label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="tabName==='0'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_FD_EDIT')||
              tabName==='1'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_HR_EDIT')||
              tabName==='2'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_EDIT')
            "
            size="small"
            type="text"
            @click="edit(scope.row)"
          >编辑</el-button>

          <el-button
            v-if="tabName==='0'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_FD_PRICE_CONTROL')||
              tabName==='1'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_HR_PRICE_CONTROL')||
              tabName==='2'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_PRICE_CONTROL')
            "
            size="small"
            type="text"
            :shop-id="shopId"
            @click="editPrice(scope.row)"
          >价格管理</el-button>

          <el-button
            v-if="tabName==='0'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_FD_RESUORCE_ON_SELL')||
              tabName==='1'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_HR_RESUORCE_ON_SELL')||
              tabName==='2'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_RESUORCE_ON_SELL')
            "
            size="small"
            type="text"
            @click="changeState(scope.row,$index)"
          >
            <span
              :class="scope.row.state==1?'':'app-text-color-success'"
            >{{ scope.row.state==1?"下架":"上架" }}</span>
          </el-button>

          <el-button
            v-if="tabName==='0'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_FD_RESUORCE_DELETE')||
              tabName==='1'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_HR_RESUORCE_DELETE')||
              tabName==='2'&&!$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_RESUORCE_DELETE')
            "
            type="text"
            size="small"
            class="app-text-color-danger"
            @click="del(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
      <el-table-column v-else label="操作" align="center" width="70" fixed="right">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="copy(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination-direction
      v-if="paginationConfig.total!==0"
      :config="paginationConfig"
      @sizeschange="sizesChange"
      @pagechange="pageChange"
    />
  </div>
</template>

<script>
import {
  getProductManageList,
  delProduct,
  updateProductState,
  updateProduct
} from '../../../api/product'
import { validateCustomPositiveInt } from '@/utils/validate'
export default {
  props: {
    tabName: {
      type: String,
      require: true
    },
    shopId: {
      type: Number,
      require: true
    },
    isCopy: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      weekOptions: [
        {
          label: '周一',
          value: '2'
        },
        {
          label: '周二',
          value: '3'
        },
        {
          label: '周三',
          value: '4'
        },
        {
          label: '周四',
          value: '5'
        },
        {
          label: '周五',
          value: '6'
        },
        {
          label: '周六',
          value: '7'
        },
        {
          label: '周日',
          value: '1'
        }
      ],
      // 状态
      tableLoading: false,
      searchLoading: false,
      // 数据
      isEditRanking: '', // 是否激活排序
      editRankingIndex: '', // 当前激活的列表索引
      originalRanking: '', // 原来的排序
      rankingForm: {
        id: '',
        ranking: ''
      },
      list: [],
      filterForm: {
        productName: '',
        productType: ''
      }
    }
  },
  watch: {
    tabName(val) {
      this.filterForm.productName = ''
      this.initData(1)
    },
    shopId(val) {
      this.initData(1)
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    /**
       * 获取数据
       */
    // 获取列表
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = page
      this.filterForm.pageSize = pageSize
      this.filterForm.shopId = this.shopId
      this.filterForm.productType = this.tabName
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = true
      getProductManageList(params)
        .then(res => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .catch(() => {})
        .finally(() => {
          this.isEditRanking = false
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    /**
       * 按钮组
       */
    // 查询
    searchByKeyword() {
      this.searchLoading = true
      this.initData(1)
    },

    // 排序
    editRanking(row, index) {
      this.rankingForm = Object.assign({}, row)
      this.isEditRanking = true
    },

    // 取消排序
    cancelEditRanking(row) {
      this.isEditRanking = false
    },

    // 确定排序
    confirmEditRanking(row) {
      if (!validateCustomPositiveInt(this.rankingForm.ranking, 4, [0, '0'])) {
        this.$message.error('请输入0或正整数')
        return
      } else if (row.ranking === this.rankingForm.ranking) {
        this.isEditRanking = false
        return
      }
      this.tableLoading = true
      updateProduct(this.rankingForm)
        .then(res => {
          this.isEditRanking = false
          this.$notify({
            title: '成功',
            message: '排序成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.initData()
        })
        .catch(() => {})
        .finally(() => {
          this.tableLoading = false
        })
    },

    // 编辑
    edit(row) {
      this.$emit('changeProductMode', {
        productMode: 'edit',
        productId: row.id
      })
    },

    // 复制
    copy(row) {
      this.$emit('hideDialogProductList', {
        productMode: 'copy',
        productId: row.id
      })
    },

    // 价格
    editPrice(row) {
      this.$emit('changeProductMode', {
        productMode: 'price',
        productId: row.id
      })
    },

    // 上下架
    changeState(row) {
      this.$confirm(
        `是否${row.state === 0 ? '上架' : '下架'}：${row.name}`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.tableLoading = true
          const params = {}
          params.productId = row.id
          params.state = row.state === 1 ? 0 : 1
          updateProductState(params)
            .then(res => {
              row.state = params.state
              this.$notify({
                title: '成功',
                message: `${row.state === 1 ? '上架' : '下架'}成功`,
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .finally(() => {
              this.tableLoading = false
            })
        })
        .catch(() => {})
    },

    // 删除
    del(row) {
      this.$confirm(`是否删除：${row.name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          const params = {
            productId: row.id
          }
          this.tableLoading = true
          delProduct(params)
            .then(res => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.initData()
            })
            .catch(() => {})
            .finally(() => {
              this.tableLoading = false
            })
        })
        .catch(() => {})
    },

    /**
       * 方法
       */
    formatAttrList(row, column) {
      let str = ''
      let i = 0
      row[column.property].forEach(v => {
        if (v.attrValue) {
          if (i === 0) {
            str += v.attrValue
          } else {
            str += '\xa0 | \xa0' + v.attrValue
          }
          i++
        }
      })
      return str || '无'
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /* 搜索 */
  .search-container {
    margin-bottom: 20px;
  }

  /* 排序相关 */
  .ranking-input {
    width: 70px;
  }
  .ranking-icon {
    font-size: 20px;
  }
</style>
